package com.practices2.view;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.practices2.R;
import com.practices2.util.LogUtil;

public class ToastWithMusic extends Toast {

	private MediaPlayer mp = null;
	private AudioManager am = null;
	private static boolean isSound = false;
	private int duration = 300;

	public static boolean isSound() {
		return isSound;
	}

	public void setSound(boolean isSound) {
		this.isSound = isSound;
	}

	public ToastWithMusic(Context context) {
		super(context);
	}

	public ToastWithMusic(Context context, boolean isSound) {
		super(context);
		this.isSound = isSound;
		mp = MediaPlayer.create(context, R.raw.notificationsound);
		am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
		// am.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume *
		// mLastProgress / 10, 0);
		mp.setVolume(am.getStreamMaxVolume(AudioManager.STREAM_MUSIC), am.getStreamMaxVolume(AudioManager.STREAM_MUSIC));

		mp.setOnCompletionListener(new OnCompletionListener() {
			@Override
			public void onCompletion(MediaPlayer mp) {
				mp.release();
			}
		});
	}

	/**
	 * 
	 * @Title: makeText
	 * @param @param context
	 * @param @param text
	 * @param @param isSound
	 * @param @return 设定文件
	 * @return ToastWithMusic 返回类型
	 * @throws
	 */
	public static ToastWithMusic makeText(Context context, CharSequence text, int duration, boolean isSound) {

		ToastWithMusic result = new ToastWithMusic(context, isSound);

		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.toast_with_music, null);

		// view.setBackgroundResource(R.drawable.dialog_bg);

		TextView tv = (TextView) view.findViewById(R.id.new_data_toast_message);
		tv.setText(text);

		DisplayMetrics dm = context.getResources().getDisplayMetrics();
		view.setMinimumWidth(dm.widthPixels);

		result.setDuration(duration);
		result.setSound(isSound);
		result.setGravity(Gravity.TOP, 0, (int) (dm.density * 360));
		result.setView(view);
		return result;
	}

	@Override
	public void show() {
		super.show();
		if (isSound) {
			mp.start();
//			LogUtil.e(ToastWithMusic.class.getName() + "mediaplayer start()");
		}
	}
}
